<template>
  <XenPageLayout
    title="员工档案"
    title-align="left"
    :show-back="true"
    navbar-bg-color="#3742fa"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    :loading="loading"
    :error="hasError"
    @retry="loadUserPersonInfo"
  >
    <!-- 主体内容 -->
    <view class="employee-container">
      <!-- 欢迎区域 -->
      <view class="welcome-section">
        <view class="user-info">
          <view class="avatar">
            <image
              v-if="userInfo?.PhotoId"
              :src="getImageUrl(userInfo.PhotoId)"
              class="avatar-img"
              mode="aspectFill"
            />
            <uni-icons
              v-else
              type="person-filled"
              size="32"
              color="#ffffff"
            ></uni-icons>
          </view>
          <view class="user-details">
            <text class="greeting">{{
              userPersonInfo?.Name || userInfo?.Name || "用户"
            }}</text>
            <text v-if="userPersonInfo?.StaffNo" class="staff-no"
              >工号：{{ userPersonInfo.StaffNo }}</text
            >
          </view>
        </view>
      </view>

      <!-- 功能模块 -->
      <view class="modules-section">
        <view class="section-header">
          <text class="section-title">功能模块</text>
        </view>

        <view class="modules-grid">
          <view
            class="module-card"
            v-for="(module, index) in employeeModules"
            :key="index"
            @click="handleModuleClick(module.url)"
          >
            <view class="module-icon" :style="{ background: module.gradient }">
              <uni-icons
                :type="module.icon as any"
                size="20"
                color="#ffffff"
              ></uni-icons>
            </view>
            <text class="module-name">{{ module.name }}</text>
          </view>
        </view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import type { IUserInfo } from "../../../pages/login/api/interface";
import Api from "../api/index";
import type { SearchResponse } from "../api/interface";

// 用户信息
const userInfo = ref<IUserInfo | null>(null);
// 用户人员信息
const userPersonInfo = ref<SearchResponse | null>(null);
// 加载状态
const loading = ref(false);
const hasError = ref(false);

// 获取图片URL - 添加时间戳防止缓存
const getImageUrl = (fileId: string) => {
  if (!fileId) return "";
  const timestamp = Date.now();
  return `${
    import.meta.env.VITE_BASE_URL
  }/api/_file/getfile/${fileId}?t=${timestamp}`;
};

// 员工档案模块数据 - 包含6个核心模块
const employeeModules = [
  {
    name: "基本信息",
    icon: "contact",
    gradient: "linear-gradient(135deg, #3742fa 0%, #2f3542 100%)",
    url: "/subpkg-hr/hr/employee/detail",
  },
  {
    name: "学习经历",
    icon: "star",
    gradient: "linear-gradient(135deg, #00bd56 0%, #00a651 100%)",
    url: "/subpkg-hr/hr/employee/education",
  },
  {
    name: "工作经历",
    icon: "wallet",
    gradient: "linear-gradient(135deg, #ff6b35 0%, #f7931e 100%)",
    url: "/subpkg-hr/hr/employee/work",
  },
  {
    name: "家庭成员",
    icon: "person-filled",
    gradient: "linear-gradient(135deg, #1abc9c 0%, #16a085 100%)",
    url: "/subpkg-hr/hr/employee/family",
  },
  {
    name: "员工履历",
    icon: "folder-add",
    gradient: "linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)",
    url: "/subpkg-hr/hr/employee/resume",
  },
  {
    name: "荣誉职称",
    icon: "medal",
    gradient: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
    url: "/subpkg-hr/hr/employee/honor",
  },
];

// 加载用户人员信息
const loadUserPersonInfo = async () => {
  if (!userInfo.value?.ITCode) {
    hasError.value = true;
    uni.showToast({
      title: "缺少用户信息",
      icon: "none",
    });
    return;
  }

  loading.value = true;
  hasError.value = false;

  try {
    const searchParams = {
      Limit: 50,
      Name: "",
      Page: 1,
      SortInfo: null,
      StaffNo: userInfo.value.ITCode,
      Phone: userInfo.value.Attributes?.CellPhone || "", // 从用户信息的Attributes中获取CellPhone
    };

    console.log("搜索参数:", searchParams);
    const res = await Api().search(searchParams);
    console.log("接口返回:", res);

    // 修改这里：访问res.Data而不是直接访问res
    if (res && res.Data && Array.isArray(res.Data) && res.Data.length > 0) {
      userPersonInfo.value = res.Data[0];
      console.log("获取用户人员信息成功:", userPersonInfo.value);
    } else {
      hasError.value = true;
      console.log("未找到人员信息，返回数据:", res);
      uni.showToast({
        title: "未找到对应人员信息",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取用户人员信息异常:", error);
    hasError.value = true;
    uni.showToast({
      title: "获取人员信息失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

const handleModuleClick = (url: string) => {
  if (!userPersonInfo.value?.ID) {
    uni.showToast({
      title: "人员信息未加载完成",
      icon: "none",
    });
    return;
  }

  // 传递人员ID参数到详情页
  const fullUrl = `${url}?id=${userPersonInfo.value.ID}`;
  uni.navigateTo({
    url: fullUrl,
  });
};

// 页面加载时获取用户信息
onMounted(() => {
  // 从本地存储获取用户信息
  const cachedUserInfo = uni.getStorageSync("userInfo");
  if (cachedUserInfo) {
    userInfo.value = cachedUserInfo;
    console.log("员工档案页面加载用户信息:", cachedUserInfo);
    // 加载人员信息
    loadUserPersonInfo();
  } else {
    hasError.value = true;
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
  }
});
</script>

<style lang="scss" scoped>
.employee-container {
  display: flex;
  flex-direction: column;

  .welcome-section {
    padding: 24px;
    flex-shrink: 0;

    .user-info {
      display: flex;
      align-items: center;
      gap: 16px;

      .avatar {
        width: 64px;
        height: 64px;
        border-radius: 32px;
        border: 3px solid rgba(255, 255, 255, 0.3);
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        flex-shrink: 0; // 防止头像被压缩

        .avatar-img {
          width: 100%;
          height: 100%;
          border-radius: 32px;
          object-fit: cover; // 确保图片比例正确
        }
      }

      .user-details {
        flex: 1;
        min-width: 0; // 允许文本区域收缩

        .greeting {
          display: block;
          color: #ffffff;
          font-size: 20px;
          font-weight: 600;
          word-break: break-all; // 长文本换行
          line-height: 1.3;
          margin-bottom: 4px;
        }

        .staff-no {
          display: block;
          color: rgba(255, 255, 255, 0.8);
          font-size: 14px;
          font-weight: 400;
          word-break: break-all; // 长文本换行
        }
      }
    }
  }

  .modules-section {
    flex: 1;
    background: #ffffff;
    border-radius: 24px 24px 0 0;
    padding: 24px;
    min-height: 0;
    display: flex;
    flex-direction: column;

    .section-header {
      margin-bottom: 20px;
      flex-shrink: 0;

      .section-title {
        color: #1a1a1a;
        font-size: 18px;
        font-weight: 600;
      }
    }

    .modules-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
      flex: 1;
      align-content: start;

      .module-card {
        background: #ffffff;
        border-radius: 16px;
        padding: 20px;
        text-align: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
        }

        .module-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0 auto 12px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .module-name {
          color: #1a1a1a;
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
  }
}
</style>
